package com.dataart.productshop.file.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import static com.dataart.productshop.Constants.*;

public class FileValidate {
	
	public static boolean validatePicture(MultipartFile mFile){
		return mFile.getOriginalFilename().matches(PICT_EXPR);
	}
	
	public static boolean validateZip(MultipartFile mFile){
		InputStream is = null;
		try{
			is = mFile.getInputStream();
		}catch(IOException ex){
			return false;
		}
		return mFile.getOriginalFilename().matches(EXT_PREFIX + "zip" + EXT_SUFFIX) && validateConvertZip(is);
	}
	
	public static boolean validateConvertZip(InputStream zipInputStream){
		try {
		
			ZipInputStream zis = new ZipInputStream(zipInputStream);
			byte[] byteBuffer = new byte[1024];

			ZipEntry ze = zis.getNextEntry();
			while(ze != null){
				String filename = ze.getName();
				if(filename.matches(EXT_PREFIX + "txt" + EXT_SUFFIX)){
					
					//read once, cause text need to be placed at the start of file
					StringBuilder bcontent = new StringBuilder();
					while(zis.read(byteBuffer) > 0){
						bcontent.append(new String(byteBuffer));
					}
					
					Pattern validatePat = Pattern.compile(WORD_EXPR.trim());
					Matcher validateMatcher = validatePat.matcher(bcontent.toString());
					
					if(validateMatcher.find()){
						zipInputStream.close();
						return true;
					}
				}
				ze = zis.getNextEntry();
			}
			zipInputStream.close();
		} catch (IOException e) {
			System.err.println("bad zip file");
		}
		return false;
	} 
	
	
}
